package com.zghhost.codedemo.sshclient;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.UserInfo;

public class Shell{
    private static final String USER="root";
    private static final String PASSWORD="asdasd";
    private static final String HOST="221.122.127.201";
    private static int DEFAULT_SSH_PORT=100;

    private static JSch jsch=new JSch();
 
    public static void main(String[] arg){
        doTry(++DEFAULT_SSH_PORT);
    }

    public static void doTry(int port){
        Session session = null;
        try{
            session = jsch.getSession(USER,HOST,DEFAULT_SSH_PORT);
            session.setPassword(PASSWORD);

            UserInfo userInfo = new UserInfo() {
                @Override
                public String getPassphrase() {
                    System.out.println("getPassphrase");
                    return null;
                }
                @Override
                public String getPassword() {
                    System.out.println("getPassword");
                    return null;
                }
                @Override
                public boolean promptPassword(String s) {
                    System.out.println("promptPassword:"+s);
                    return false;
                }
                @Override
                public boolean promptPassphrase(String s) {
                    System.out.println("promptPassphrase:"+s);
                    return false;
                }
                @Override
                public boolean promptYesNo(String s) {
                    System.out.println("promptYesNo:"+s);
                    return true;//notice here!
                }
                @Override
                public void showMessage(String s) {
                    System.out.println("showMessage:"+s);
                }
            };
            session.setUserInfo(userInfo);
            session.connect(10);   // making a connection with timeout.
            Channel channel=session.openChannel("shell");
            channel.setInputStream(System.in);
            channel.setOutputStream(System.out);
            channel.connect(3*1000);
        }catch(Exception e){
            String msg = e.getMessage();
            if(msg.indexOf("Auth") != -1){
                System.out.println("目标端口："+DEFAULT_SSH_PORT);
            }else{
                System.out.println("端口："+DEFAULT_SSH_PORT+" 无效("+msg+")");
                doTry(++DEFAULT_SSH_PORT);
            }
        }finally {
            session.disconnect();
        }
    }
}